package core.proto.search;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;

import core.proto.AllComponents;
import core.proto.PaintDoc;
import core.proto.TextHighlighter;
import core.proto.Util;

public class SearchPopupDocumentListener implements DocumentListener {

	Popup popup;
	JComponent field;
	String text;
	MouseListener listener; 
	boolean preventPopup = false;
	public static Object popupLock = new Object();
	public  SearchPopupDocumentListener (JComponent field, String text) {
		popup = null;
		this.field = field;
		this.text = text;
		this.listener = new MouseAdapter() {
			public void mouseClicked(MouseEvent e)
			{
				popup.hide();
				popup = null;
			}
		};
	}

	@Override
	public void changedUpdate(DocumentEvent de) {
		// No op
	}

	@Override
	public void insertUpdate(DocumentEvent de) {
		synchronized(popupLock){
			if (popup == null && !preventPopup) {
				// create and show popup! 
				try{
						Point loc = field.getLocationOnScreen();
						JToolTip tooltip = field.createToolTip();
						tooltip.setTipText(text);
						tooltip.addMouseListener(listener);
						popup = PopupFactory.getSharedInstance().getPopup(null, tooltip, loc.x, loc.y - 15);
							
						popup.show();
				}catch(NullPointerException e){

				}
				
			}
		}
	}

	@Override
	public void removeUpdate(DocumentEvent de) {
		String text;
		try {
			text = de.getDocument().getText(0, de.getDocument().getLength());
			if (text.length() == 0 && popup != null){
				popup.hide();
				popup = null;
			}
		} catch (BadLocationException e) {
		}
	}
	
	public void preventPopupToggle(){
		if(preventPopup){
			preventPopup = false;
		}
		else{
			preventPopup = true;
		}
	}
	
	public void setField(JComponent c){
		field = c;
	}
}
